import { createSlice } from "@reduxjs/toolkit";
// import { request } from "@/utils/request";
import { setToken as _setToken, getToken, removeToken } from "@/utils/token";
import { LoginAPI, userInfoAPI } from "@/api/user";
const userStore = createSlice({
    name: 'user',
    initialState: {
        // 如果本地有值直接获取本地的值,如果没有则获取空串
        token: getToken() || '',
        userInfo: {}
    },
    reducers: {
       setToken(state, action){
          state.token = action.payload
          _setToken(state.token)
        },
        setUserInfo(state, action) {
           state.userInfo = action.payload
        },
        // 清楚用户信息和token的方法
        remUserInfo(state, action) {
            state.userInfo = {}
            state.token = ''
            // 清楚本地token
            removeToken()
        }
    },
})



const { setToken , setUserInfo , remUserInfo} = userStore.actions
const useReducer = userStore.reducer

 // 封装异步方法
 const feachLogin = (loginData) => {
     return async (dispatch) => {
       const res = await LoginAPI(loginData)
       dispatch(setToken(res.data.token))
     }
 }
// 获取用户信息的异步方法
const feachUserInfo = () => {
    return async (dispatch) => {
        const res = await userInfoAPI()
        dispatch(setUserInfo(res.data))
    }
}
export {
    setToken,
    feachLogin,
    feachUserInfo,
    remUserInfo
}

export default useReducer